import appkey from './appkey.js'
import api from './api.js'
var util = require("./libs.js")

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}
/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: 'https://api.weixin.qq.com/sns/jscode2session',
      data: data,
      method: method,
      success: function (res) {
        if (res.statusCode == 200) {
         let arr = wx.getStorageSync('userInfo');
         util.request(api.login, {
            openid:res.data.openid,
            nickname: arr.nickName,
            avatar: arr.avatarUrl,
            gander: arr.gender,
            province: arr.province,
            city: arr.city }, 'POST').then(res => {
              if (res.error_code === 0) {
              //存储用户信息
              
              wx.setStorageSync('uid', res.data.user.id);
              wx.setStorageSync('userInfo', res.data.user);
            }else{
                  reject(res);
                }
              }).catch((err) => {
                reject(err);
              })
        } else {
          reject(res.errMsg);
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}
function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        resolve(res);
        wx.setStorageSync('userInfo',res.userInfo);
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}
module.exports = {
  formatTime,
  login,
  request,
  getUserInfo
}